Building and Explaining an Anomaly Detector using AutoMLx - Experimental

by the Oracle AutoMLx Team


AutoMLx Anomaly Detection Demo version 23.1.1.

Copyright (c) 2023 Oracle, Inc.

Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/

Overview of this Notebook¶

In this notebook we will build an anomaly detection model using the experimental, fully unsupervised anomaly detection pipeline in Oracle AutoMLx for the public Credit Card Fraud dataset. The dataset is a binary anomaly detection dataset, and more details about the dataset can be found at https://www.openml.org/d/1597. We explore the various options provided by the Oracle AutoMLx tool, allowing the user to control the AutoML training process. We then evaluate the different models trained by AutoML. Finally we provide an overview of the possibilites that Oracle AutoMLx provides for explaining the predictions of the tuned model.


Prerequisites¶

  • Experience level: novice (Python and Machine Learning)
  • Professional experience: some industry experience

Business Use¶

Data analytics and modeling problems using Machine Learning (ML) are becoming popular and often rely on data science expertise to build accurate ML models. Such modeling tasks primarily involve the following steps:

  • Preprocess dataset (clean, impute, engineer features, normalize).
  • Pick an appropriate model for the given dataset and prediction task at hand.
  • Tune the chosen model’s hyperparameters for the given dataset.

All of these steps are significantly time consuming and heavily rely on data scientist expertise. Unfortunately, to make this problem harder, the best feature subset, model, and hyperparameter choice widely varies with the dataset and the prediction task. Hence, there is no one-size-fits-all solution to achieve reasonably good model performance. Using a simple Python API, AutoML can quickly (faster) jump-start the datascience process with an accurately-tuned model and appropriate features for a given prediction task.

Table of Contents¶

  • 0. Setup
  • 1. Load the Credit Card dataset
  • 2. AutoML
    • 2.0. Set the Engine
    • 2.1. Create an Instance of AutoML
    • 2.2. Train a Model using AutoML
    • 2.3. Analyze the AutoML optimization process
      • 2.3.1. Algorithm Selection
      • 2.3.2. Hyperparameter Tuning
    • 2.4. Specify a Time Budget to AutoML
  • 3. Machine Learning Explainability (MLX)
    • 3.1. Initialize an MLExplainer
    • 3.2. Model Explanations (Global Feature Importance)
    • 3.3. Feature Dependence Explanations
    • 3.4 Prediction Explanations (Local Feature Importance)
    • 3.5 Aggregate Local Feature Importance & Local Feature Importance Built-in Sampling
    • 3.6 Advanced Feature Importance Options
      • 3.6.1. Change the number of iterations
      • 3.6.2. Include the effects of feature interactions (with Shapley feature importance)
    • 3.7. Advanced Feature Dependence Options (ALE)
  • References

Setup¶

Basic setup for the Notebook.

In [1]:
! pip install seaborn==0.12.1
! pip install rdata==0.9

%matplotlib inline
%load_ext autoreload
%autoreload 2
Requirement already satisfied: seaborn==0.12.1 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (0.12.1)
Requirement already satisfied: pandas>=0.25 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from seaborn==0.12.1) (1.4.1)
Requirement already satisfied: matplotlib!=3.6.1,>=3.1 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from seaborn==0.12.1) (3.5.1)
Requirement already satisfied: numpy>=1.17 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from seaborn==0.12.1) (1.22.2)
Requirement already satisfied: cycler>=0.10 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from matplotlib!=3.6.1,>=3.1->seaborn==0.12.1) (0.10.0)
Requirement already satisfied: python-dateutil>=2.7 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from matplotlib!=3.6.1,>=3.1->seaborn==0.12.1) (2.8.2)
Requirement already satisfied: kiwisolver>=1.0.1 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from matplotlib!=3.6.1,>=3.1->seaborn==0.12.1) (1.1.0)
Requirement already satisfied: fonttools>=4.22.0 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from matplotlib!=3.6.1,>=3.1->seaborn==0.12.1) (4.29.1)
Requirement already satisfied: pyparsing>=2.2.1 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from matplotlib!=3.6.1,>=3.1->seaborn==0.12.1) (2.4.7)
Requirement already satisfied: packaging>=20.0 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from matplotlib!=3.6.1,>=3.1->seaborn==0.12.1) (21.3)
Requirement already satisfied: pillow>=6.2.0 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from matplotlib!=3.6.1,>=3.1->seaborn==0.12.1) (9.0.1)
Requirement already satisfied: pytz>=2020.1 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from pandas>=0.25->seaborn==0.12.1) (2022.1)
Requirement already satisfied: six in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from cycler>=0.10->matplotlib!=3.6.1,>=3.1->seaborn==0.12.1) (1.16.0)
Requirement already satisfied: setuptools in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from kiwisolver>=1.0.1->matplotlib!=3.6.1,>=3.1->seaborn==0.12.1) (62.3.4)

[notice] A new release of pip available: 22.2.2 -> 23.0
[notice] To update, run: pip install --upgrade pip
Requirement already satisfied: rdata==0.9 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (0.9)
Requirement already satisfied: numpy in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from rdata==0.9) (1.22.2)
Requirement already satisfied: xarray in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from rdata==0.9) (2023.1.0)
Requirement already satisfied: pandas in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from rdata==0.9) (1.4.1)
Requirement already satisfied: pytz>=2020.1 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from pandas->rdata==0.9) (2022.1)
Requirement already satisfied: python-dateutil>=2.8.1 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from pandas->rdata==0.9) (2.8.2)
Requirement already satisfied: packaging>=21.3 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from xarray->rdata==0.9) (21.3)
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from packaging>=21.3->xarray->rdata==0.9) (2.4.7)
Requirement already satisfied: six>=1.5 in /scratch_user/ypushak/automl-3/automl/py_3.8.7/lib/python3.8/site-packages (from python-dateutil>=2.8.1->pandas->rdata==0.9) (1.16.0)

[notice] A new release of pip available: 22.2.2 -> 23.0
[notice] To update, run: pip install --upgrade pip

Load the required modules.

In [2]:
import gzip
import urllib
import rdata
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import f1_score, confusion_matrix
from sklearn.model_selection import train_test_split
from pyod.models.iforest import IForest

# Settings for plots
plt.rcParams['figure.figsize'] = [10, 7]
plt.rcParams['font.size'] = 15
sns.set(color_codes=True)
sns.set(font_scale=1.5)
sns.set_palette("bright")
sns.set_style("whitegrid")

import automl
from automl import init

Load the Credit Card Fraud Dataset¶

We start by retrieving and reading in the dataset from provided URL.

In [3]:
url = "http://www.ulb.ac.be/di/map/adalpozz/data/creditcard.Rdata"
dst_path = "./creditcard.Rdata"

with open(dst_path, 'wb') as fout:
    fout.write(urllib.request.urlopen(url).read())
parsed_res = rdata.parser.parse_file(dst_path)
res = rdata.conversion.convert(parsed_res)
dataset = res['creditcard'].reset_index().drop(['Time'], axis=1)

In this case, the target is identified by the Class column.

In [4]:
y = dataset.loc[:, 'Class']

We reduce the total number of features to 20 to have a reasonable training time for this demonstration.

In [5]:
df = dataset.iloc[:, :20]

Our pipeline currently only allows the indices types to be strings. Make sure to convert the indices types before any use of the pipeline

In [6]:
df.columns = df.columns.astype(str)

Since the dataset is not split into training and validation sets by default, we now split it into training (60%) and test (40%) datasets. The training set will be used to create a Machine Learning model using AutoML, and the test set will be used to evaluate the model's performance on unseen data.

In [7]:
X_train, X_test, y_train, y_test = train_test_split(df, y, train_size=0.6, random_state=0, stratify=y)
                                                 
X_train.shape, X_test.shape
Out[7]:
((170884, 20), (113923, 20))

Again to keep the training time reasonable, we also downsample to use 5% of the total training set.

In [8]:
X_train, _, y_train, _ = train_test_split(X_train, y_train, train_size=0.05, random_state=0, stratify=y_train)

X_train.shape
Out[8]:
(8544, 20)

We also need to reset the indexes after our downsampling.

In [9]:
X_train.reset_index(drop=True, inplace=True)
y_train.reset_index(drop=True, inplace=True)

Lets look at a few of the samples in the training dataset.

In [10]:
X_train.head()
Out[10]:
index V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19
0 62605 -0.716073 0.225322 3.761183 3.207240 -0.495804 1.865745 -0.678000 0.458706 -0.009656 0.484059 0.026032 1.070390 0.905135 -1.490118 -1.857273 -0.478333 0.224669 0.763987 1.715066
1 61794 -0.287669 1.355348 0.607857 0.564008 0.823146 -0.623391 0.846476 -0.026066 -0.968745 -0.953380 1.469807 0.470426 0.426923 -1.388217 0.138532 0.771883 0.503981 1.289862 -0.073898
2 47133 -1.360701 0.068936 1.547622 0.968746 -2.539901 1.505830 2.200844 -0.087798 1.034511 -0.918203 -0.866630 0.289333 -1.194264 -0.939673 -2.124787 -0.923653 0.630370 -1.355050 -0.591845
3 103624 -1.167623 -0.206586 1.155390 -1.460830 -1.248562 -0.637028 0.015802 0.154537 -3.190664 0.822285 0.061631 -0.513346 1.103738 0.029712 0.751646 -1.206843 1.420112 -0.898657 0.463735
4 235662 -0.771096 -0.882119 -0.583668 -0.087184 -1.984118 0.750064 1.243510 0.479466 0.410805 -1.674414 -0.841014 -0.267114 0.487951 -1.263536 1.160706 1.723230 -0.083639 1.335979 -1.330248

The Credit card fraud dataset contains numerical data.

In [11]:
pd.DataFrame({'Data type': X_train.dtypes}).T
Out[11]:
index V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19
Data type object float64 float64 float64 float64 float64 float64 float64 float64 float64 float64 float64 float64 float64 float64 float64 float64 float64 float64 float64

The Oracle AutoMLx solution automatically handles missing values by dropping features with too many missing values, and filling in the remaining missing values based on the feature type.

In this case, there are no such missing values in our training dataset.

In [12]:
pd.DataFrame({'% missing values': X_train.isnull().sum() * 100 / len(df)}).T
Out[12]:
index V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19
% missing values 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0

We visualize the distribution of the target variable in the data. The dataset is heavily unbalanced, as is often the case in the anomaly detection use-case.

In [13]:
y_df = pd.DataFrame(y_train)
y_df.columns = ['income']

ax = sns.countplot(x='income', data=y_df)
ax.set(xlabel='Anomaly', xticklabels=['False', 'True'])
ax.bar_label(ax.containers[0])
Out[13]:
[Text(0, 0, '8529'), Text(0, 0, '15')]

AutoML¶

Setting the engine¶

The AutoML pipeline offers the function init, which allows to initialize the parallel engine. By default, the AutoML pipeline uses the dask parallel engine. One can also set the engine to local, which uses python's multiprocessing library for parallelism instead.

In [14]:
init(engine='local')
[2023-02-10 12:22:43,561] [automl.xengine] Local ProcessPool execution (n_jobs=40)

Create an instance of AutoML for Unsupervised Anomaly Detection - Experimental Feature¶

The Oracle AutoMLx solution provides a pipeline that automatically finds a tuned model given a prediction task and a training dataset. In particular it allows to find a tuned model for the task of Unsupervised Anomaly Detection (UAD), where the training labels (whether a training point is an anomaly or not) are unknown.

The AutoML UAD Pipeline consists of three main modules:

  • Preprocessing : Clean, impute, engineer, and normalize features.
  • Algorithm Selection : Identify the right algorithm for a given dataset, choosing from amongst the following Outlier Detectors (OD):
    • IsolationForestOD
    • SubspaceOD
    • HistogramOD
    • ClusteringLocalFactorOD
    • PrincipalCompOD
    • MinCovOD
    • AutoEncoder
    • KNearestNeighborsOD
    • OneClassSVMOD
  • Hyperparameter Tuning : Find the best model hyperparameters that maximize score for the given dataset.

All these pieces are readily combined into a simple AutoML pipeline which automates the entire Machine Learning process with minimal user input/interaction.

Train a model using Oracle AutoMLx¶

The AutoML API is quite simple to work with. We create an instance of the pipeline. Next, the training data is passed to the fit() function which successively executes the three previously mentioned modules.

A model is then generated and can be used for prediction tasks. We then evaluate the performance of the model on unseen data (X_test) using the F1-score.

In [15]:
est = automl.Pipeline(task='anomaly_detection', score_metric='unsupervised_unify95')
est.fit(X_train, y=None) 
# In the above line, even though y_train is available for this dataset, 
# we ignore it to treat the problem as an unsupervised problem
y_pred = est.predict(X_test)

score_default = f1_score(y_test.astype(int), y_pred)

print(f'F1-Score on test data : {score_default}')
[2023-02-10 12:22:43,968] [automl.pipeline] Random state (7) is used for model builds
[2023-02-10 12:22:44,005] [automl.pipeline] Dataset shape: (8544, 20)
[2023-02-10 12:22:44,079] [automl.pipeline] Running Auto-Preprocessing
[2023-02-10 12:22:44,132] [automl.pipeline] Preprocessing completed. Updated Dataset shape: (8544, 19), cv: None
[2023-02-10 12:22:45,402] [automl.pipeline] Running Model Selection
[2023-02-10 12:23:05,178] [automl.pipeline] Model Selection completed. Selected model: ['MinCovOD']
[2023-02-10 12:23:05,180] [automl.pipeline] Adaptive Sampling Disabled
[2023-02-10 12:23:05,180] [automl.pipeline] Adaptive Sampling Completed. Updated Dataset Shape: (8544, 19), Valid Shape: (8544, 19), CV: None, Class counts: N/A
[2023-02-10 12:23:05,181] [automl.pipeline] Starting Feature Selection 0. Dataset Shape: (8544, 19)
[2023-02-10 12:23:05,259] [automl.pipeline] Feature Selection Disabled
[2023-02-10 12:23:05,260] [automl.pipeline] Using all features: Index(['V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11',
       'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19'],
      dtype='object')
[2023-02-10 12:23:05,285] [automl.pipeline] Feature Selection 0 completed. Updated Dataset shape: (8544, 19)
[2023-02-10 12:23:05,355] [automl.pipeline] Tuning MinCovOD
[2023-02-10 12:23:11,496] [automl.pipeline] Tuning completed. Best params: {'assume_centered': False, 'support_fraction': 0.8407590493953608}
[2023-02-10 12:23:11,529] [automl.pipeline] (Re)fitting Pipeline
[2023-02-10 12:23:14,193] [automl.xengine] Local ProcessPool execution (n_jobs=40)
[2023-02-10 12:23:14,285] [automl.pipeline] AutoML completed. Time taken - 29.849 sec
F1-Score on test data : 0.6743119266055047

Analyze the AutoML optimization process¶

During AutoML training, a summary of the optimization process is logged, containing:

  • Information about the training data.
  • Information about the AutoML pipeline, such as:
    • Selected algorithm that was the best choice for this data;
    • Selected hyperparameters for the selected algorithm.

AutoML provides a print_summary() API to output all the different trials performed.

In [16]:
est.print_summary()
Training Dataset size (8544, 20)
Validation Dataset size None
CV None
Optimization Metric unsupervised_unify95
Selected Features Index(['V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19'], dtype='object')
Selected Algorithm MinCovOD
Time taken 27.5215
Selected Hyperparameters {'assume_centered': False, 'contamination': 0.0017556179775280898, 'random_state': 7, 'store_precision': True, 'support_fraction': 0.8407590493953608}
AutoML version 23.1.1
Python version 3.8.7 (default, Aug 25 2022, 13:59:56) \n[GCC 8.5.0 20210514 (Red Hat 8.5.0-10.1.0.1)]
Algorithm #Samples #Features Mean Validation Score Hyperparameters CPU Time Memory Usage (GB)
MinCovOD_HT 8544 19 0.9924 {'assume_centered': False, 'support_fraction': 0.840764027691241} 1.9822 (0.004589080810546875, None)
MinCovOD_HT 8544 19 0.9924 {'assume_centered': False, 'support_fraction': 0.8407590493953608} 1.9997 (0.0047760009765625, None)
MinCovOD_HT 8544 19 0.9916 {'assume_centered': True, 'support_fraction': 0.8407590493953608} 1.9894 (0.004604339599609375, None)
MinCovOD_HT 8544 19 0.9916 {'assume_centered': True, 'support_fraction': 0.840764027691241} 2.0254 (0.004791259765625, None)
MinCovOD_AS 8544 19 0.9905 {'assume_centered': False, 'support_fraction': None} 3.4497 0.0067
... ... ... ... ... ... ...
KNearestNeighborsOD_AS 8544 19 0.8506 {'n_neighbors': 5, 'method': 'largest', 'radius': 1.0} 7.5791 0.6818
AutoEncoder_AS 8544 19 0.8295 {'activation': 'relu', 'dropout': 0.05, 'encoder_length': 2, 'layer_size_growth': 'exponential', 'middle_layer_size': 2} 2.6912 0.014
IsolationForestOD_AS 8544 19 0.8217 {'n_estimators': 100, 'max_samples': 'auto', 'max_features': 1.0} 1.1162 0.0034
HistogramOD_AS 8544 19 0.8021 {'n_bins': 10, 'alpha': 0.1, 'tol': 0.5} 2.4784 0.0215
OneClassSVMOD_AS 8544 19 0.7974 {'gamma': 'auto', 'kernel': 'rbf', 'nu': 0.5} 10.7512 0.1737

We also provide the capability to visualize the results of each stage of the AutoML pipeline.

Algorithm Selection¶

The plot below shows the scores predicted by Algorithm Selection for each algorithm. The horizontal line shows the average score across all algorithms. Algorithms below the line are colored turquoise, whereas those with a score higher than the mean are colored teal. Here we can see that the MinCovOD achieved the highest predicted score (orange bar), and is chosen for subsequent stages of the Pipeline.

In [17]:
# Each trial is a tuple of
# (algorithm, no. samples, no. features, mean CV score, hyperparameters, 
# all CV scores, total CV time (s), memory usage (Gb))
trials = est.model_selection_trials_
colors = []
scores = [x[3] for x in trials]
models = [x[0] for x in trials]
y_margin = 0.10 * (max(scores) - min(scores))
s = pd.Series(scores, index=models).sort_values(ascending=False)

for f in s.keys():
    if f == '{}_AS'.format(est.selected_model_):
        colors.append('orange')
    elif s[f] >= s.mean():
        colors.append('teal')
    else:
        colors.append('turquoise')
        

fig, ax = plt.subplots(1)
ax.set_title("Algorithm Selection Trials")
ax.set_ylim(min(scores) - y_margin, max(scores) + y_margin)
ax.set_ylabel(est.inferred_score_metric[0])
s.plot.bar(ax=ax, color=colors, edgecolor='black')
ax.axhline(y=s.mean(), color='black', linewidth=0.5)
plt.show()

Hyperparameter Tuning¶

Hyperparameter Tuning is the last stage of the AutoML pipeline, and focuses on improving the chosen algorithm's score on the dataset. We use a novel algorithm to search across many hyperparameters dimensions, and converge automatically when optimal hyperparameters are identified. Each trial in the graph below represents a particular hyperparameters configuration for the selected model.

In [18]:
# Each trial is a tuple of
# (algorithm, no. samples, no. features, mean CV score, hyperparameters, 
# all CV scores, total CV time (s), memory usage (Gb))
trials = est.tuning_trials_
scores = [x[3] for x in reversed(trials)]
y_margin = 0.10 * (max(scores) - min(scores))


fig, ax = plt.subplots(1)
ax.set_title("Hyperparameter Tuning Trials")
ax.set_xlabel("Iteration $n$")
ax.set_ylabel(est.inferred_score_metric[0])
ax.grid(color='g', linestyle='-', linewidth=0.1)
ax.set_ylim(min(scores) - y_margin, max(scores) + y_margin)
ax.plot(range(1, len(trials) + 1), scores, 'k:', marker="s", color='teal', markersize=3)
plt.show()

Confusion Matrix¶

Evaluating an anomaly detection model is slightly more involved. Essentially, we would like to know when the model was wrong and when the model was right. We use a Confusion Matrix to help us visualize the model's behavior.

In [19]:
cm = confusion_matrix(y_test.astype(int), y_pred, labels=[False, True])
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]

df_cm = pd.DataFrame(cm)
df_cm = df_cm * 100

ax = sns.heatmap(df_cm, annot=True, fmt='.2f', cbar=False, 
            xticklabels=['Normal', 'Fraud'], yticklabels=['Normal', 'Fraud'])

ax.set_xlabel('Prediction')
ax.set_ylabel('Actual')
Out[19]:
Text(58.5, 0.5, 'Actual')

Specify a time budget to Oracle AutoMLx¶

The Oracle AutoMLx tool also allows a user to specify a time budget in seconds. Given the small size of this dataset, we give a small time budget of 10 seconds using the time_budget argument to fit().

In [20]:
est_timebudget = automl.Pipeline(task='anomaly_detection', score_metric='unsupervised_unify95')
est_timebudget.fit(X_train, y=None, time_budget=10)
y_pred = est_timebudget.predict(X_test)
score_timebudget = f1_score(y_test.astype(int), y_pred)

print(f'F1-Score on test data : {score_timebudget}')
[2023-02-10 12:23:18,853] [automl.pipeline] Random state (7) is used for model builds
[2023-02-10 12:23:18,892] [automl.pipeline] Dataset shape: (8544, 20)
[2023-02-10 12:23:18,975] [automl.pipeline] Running Auto-Preprocessing
[2023-02-10 12:23:19,028] [automl.pipeline] Preprocessing completed. Updated Dataset shape: (8544, 19), cv: None
[2023-02-10 12:23:19,160] [automl.pipeline] Running Model Selection
Time budget exceeded by 1.82s, resetting XEngine
Timebudget Exceeded or Timedout completed 7/8, 0 tasks timedout
[2023-02-10 12:23:30,785] [automl.pipeline] Model Selection completed. Selected model: ['MinCovOD']
[2023-02-10 12:23:30,786] [automl.pipeline] Adaptive Sampling Disabled
[2023-02-10 12:23:30,786] [automl.pipeline] Adaptive Sampling Completed. Updated Dataset Shape: (8544, 19), Valid Shape: (8544, 19), CV: None, Class counts: N/A
[2023-02-10 12:23:30,787] [automl.pipeline] Starting Feature Selection 0. Dataset Shape: (8544, 19)
[2023-02-10 12:23:30,856] [automl.pipeline] Timebudget exhausted. Skipping Feature Selection
[2023-02-10 12:23:30,857] [automl.pipeline] Using all features: Index(['V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11',
       'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19'],
      dtype='object')
[2023-02-10 12:23:30,881] [automl.pipeline] Feature Selection 0 completed. Updated Dataset shape: (8544, 19)
[2023-02-10 12:23:30,950] [automl.pipeline] Timebudget exhausted. Skipping Hyperparameter Optimization for MinCovOD
[2023-02-10 12:23:30,975] [automl.pipeline] (Re)fitting Pipeline
[2023-02-10 12:23:35,117] [automl.xengine] Local ProcessPool execution (n_jobs=40)
[2023-02-10 12:23:35,205] [automl.pipeline] AutoML completed. Time taken - 15.891 sec
F1-Score on test data : 0.3275109170305677

Machine Learning Explainability¶

For a variety of decision-making tasks, getting only a prediction as model output is not sufficient. A user may wish to know why the model outputs that prediction, or which data features are relevant for that prediction. For that purpose the Oracle AutoMLx solution defines the MLExplainer object, which allows to compute a variety of model explanations.

Initialize an MLExplainer¶

The MLExplainer object takes as argument the trained model, the training data and the task. If you know the labels for your dataset, you may provide them; however, since we are dealing with anomaly detection they are optional. When the labels are not provided, we will use the model's predictions instead.

In [21]:
explainer = automl.MLExplainer(est,
                               X_train,
                               target_names=['Normal', 'Anomaly'],
                               task='anomaly_detection')

Model Explanations (Global Feature Importance)¶

The notion of Global Feature Importance intuitively measures how much the model's performance (relative to the model's original predictions or the provided train labels, if available) would change if a given feature were dropped from the dataset, and the model was retrained. (Note that this is unlike the default explainers for classification and regression tasks, which explain the model as if it were not retrained. Also unlike these supervised explainers, the anomaly detection explainer does not support interventional explanations.) Note that this notion of feature importance still considers each feature independently from all other features.

Compute the importance¶

By default we use a permutation method to successively measure the importance of each feature. Such a method therefore runs in linear time with respect to the number of features in the dataset.

The method explain_model() allows to compute such feature importances. It also provides 95% confidence intervals for each feature importance.

In [22]:
result_explain_model_default = explainer.explain_model()

Visualization¶

There are two options to show the explanation's results:

  • to_dataframe() will return a dataframe of the results.
  • show_in_notebook() will show the results as a bar plot.

The features are returned in decreasing order of importance.

In [23]:
result_explain_model_default.to_dataframe()
Out[23]:
feature attribution upper_bound lower_bound
0 V12 0.000103 0.000245 -0.000038
1 V6 0.000096 0.000227 -0.000036
2 V3 0.000076 0.000205 -0.000052
3 V10 0.000076 0.000205 -0.000052
4 V17 0.000061 0.000188 -0.000067
5 V18 0.000059 0.000181 -0.000064
6 V4 0.000058 0.000181 -0.000064
7 V16 0.000057 0.000176 -0.000062
8 V15 0.000054 0.000167 -0.000059
9 V11 0.000038 0.000140 -0.000065
10 V1 0.000000 0.000000 0.000000
11 V13 0.000000 0.000000 0.000000
12 V14 0.000000 0.000000 0.000000
13 V19 0.000000 0.000000 0.000000
14 V2 0.000000 0.000000 0.000000
15 V5 0.000000 0.000000 0.000000
16 V7 0.000000 0.000000 0.000000
17 V8 0.000000 0.000000 0.000000
18 V9 0.000000 0.000000 0.000000
In [24]:
result_explain_model_default.show_in_notebook()

Feature Dependence Explanations (Partial Dependence Plots)¶

Another way to measure dependency on a feature is through a partial dependence plot (PDP). Given a dataset, a PDP displays the average output of the model as a function of the value of the selected set of features.

The X-axis is the value of the feature V17 and the y-axis is the corresponding outputted price. Since we are considering the whole dataset, while the shaded interval corresponds to a 95% confidence interval for the average.

The histogram on top shows the distribution of the value of the feature V17 in the dataset.

In [25]:
result_explain_feature_dependence_default = explainer.explain_feature_dependence('V17')
result_explain_feature_dependence_default.show_in_notebook()

Prediction Explanations (Local Feature Importance)¶

Given a data sample, one can also obtain the local importance, which is the importance of the features for the model's prediction on that sample. In the following cell, we consider sample $1$. The function explain_prediction() computes the local importance for a given sample.

In the plot, V8=0.8878 means that the value of feature V8 for that sample is 0.8878. Removing that feature and retraining the model would change the model's prediction by the magnitude of the bar. That is, in this case, the model's prediction for the probability that the point is anomalous is approximately 0.4% larger because the model was able to observe the value for V8.

In [26]:
anomaly_indices = np.where(y_pred == 1)[0]
In [27]:
index = anomaly_indices[0]
result_explain_prediction_default = explainer.explain_prediction(X_train.iloc[index:index+1,:])
result_explain_prediction_default[0].show_in_notebook()

Aggregate Local Feature Importance & Local Feature Importance Built-in Sampling¶

We now summarize all of the individual local feature importance explanations into one single aggregate explanation.

To speed up the computation of the local feature importance explanations, we enable the explainer's built-in sampling.

In [28]:
explainer.configure_explain_prediction(sampling={'technique': 'random', 'n_samples': 2000})
In [29]:
# We select 5 random instances here as an example and show the aggregate explanation of those instances.
local_explanations = explainer.explain_prediction(X_train.sample(n=5))
alfi = explainer.aggregate(explanations=local_explanations)
alfi.show_in_notebook()
Out[29]:

Advanced Feature Importance Configurations¶

We now display more advanced configuration for computing feature importance. Here, we will explain a custom isolation forest model from the PyOD package. Note that the MLExplainer object is capable to explain any anomaly detection model, as long as the model follows a pyod-style interface with the predict and predict_proba fucntions.

In [30]:
pyod_model = IForest()
pyod_model.fit(X_train, y_train)

y_pred = pd.Series(pyod_model.predict(X_train), index=X_train.index)
explainer_pyod = automl.MLExplainer(pyod_model,
                                    X_train,
                                    target_names=['Normal', 'Anomaly'],
                                    task="anomaly_detection")

Changing the number of iterations¶

One can modify the number of iterations n_iter used to evaluate the global importance of the model, or the local importance of a prediction.

Increasing n_iter requires a linear increase in computation time. It however provides more accurate importance estimates, thereby decreasing the variance in repeated calls to explain_model/explain_prediction.

The default value is auto, which selects a suitable default value based on the choice of the method of explanation. Decreasing the number of iterations to 1 also means that the confidence intervals are no longer available.

In this example, because we are explaining a different model, the order of the most important features has changed.

In [31]:
result_explain_model_increase_n_iter = explainer_pyod.explain_model(n_iter=1)
result_explain_model_increase_n_iter.show_in_notebook()

Including the effects of feature interactions (with Shapley feature importance)¶

The Oracle AutoMLx solution allows one to change the effect of feature interactions. This can be done through the tabulator_type argument of both global and local importance methods.

tabulator_type can be set to one of those three options: permutation, kernel_shap, shapley, shap_pi

  • permutation: This value is the default method in the MLExplainer object, and the behaviour was described above

  • kernel_shap: Feature importance attributions will be calculated using an approximation of the Shapley value method. It typically provides relatively high-quality approximations; however, it currently does not provide confidence intervals.

  • shapley: Feature importance is computed using the popular game-theoretic Shapley value method. Technically, this measures the importance of each feature while including the effect of all feature interactions. As a result, it runs in exponential time with respect to the number of features in the dataset. This method also includes the interaction effects of the other features, which means that if two features contain duplicate information, they will be less important. Note that the interpretation of this method's result is a bit different from the permutation method's result. An interested reader may find this a good source for learning more about it.

  • shap_pi: Feature importance attributions will be computed using an approximation of the Shapley value method. It runs in linear time, but may miss the effect of interactions between some features, which may therefore produce lower-quality results. Most likely, you will notice that this method yields larger confidence intervals than the other two.

Summary: permutation can miss important features for AD. Exact SHAP (shapley) doesn't, but it is exponential in running time. kernel_shap is an approximation of exact SHAP method that does not provide confidence intervals. shap_pi is linear, thus faster than exact SHAP and kernel_shap but unstable and very random leads to lower quality approximations.

Local feature importance with kernel_shap¶
In [32]:
explainer_pyod.configure_explain_prediction(tabulator_type="kernel_shap", 
                                            sampling={'technique': 'random', 'n_samples': 2000})
In [33]:
anomaly_indices = np.where(y_pred == 1)[0]
index = anomaly_indices[0]
result_explain_prediction_kernel_shap = explainer_pyod.explain_prediction(X_train.iloc[index:index+1,:])
result_explain_prediction_kernel_shap[0].show_in_notebook()

Advanced Feature Dependence Options (ALE)¶

We now show how to use an alternative method for computing feature dependence: accumulated local effects (ALE). ALE explanations are sometimes considered a better alternative to PDPs when features are correlated, because it does not evaluate the model outside of its training distribution in these cases. For more information, see https://christophm.github.io/interpretable-ml-book/ale.html.

Given a dataset, an ALE displays the average change in the output of the model, accumulated of multiple small changes in one or two features, when all other features are held fixed. By default, the ALE explanations are centered around 0, and thus, unlike PDPs, ALEs show the change in the prediction measured by changing a given feature, rather than the average model's prediction for a particular feature value.

The X-axis is the value of the V17 feature and the y-axis is the corresponding computed ALE (price unit).

The histogram on top shows the distribution of the value of the V17 feature in the dataset.

In [34]:
explainer_pyod.configure_explain_feature_dependence(explanation_type='ale')
result_explain_feature_dependence_default = explainer_pyod.explain_feature_dependence(['V17'])
result_explain_feature_dependence_default.show_in_notebook()

References¶

  • More examples and details: http://automl.oraclecorp.com/
  • Oracle AutoML http://www.vldb.org/pvldb/vol13/p3166-yakovlev.pdf
  • scikit-learn https://scikit-learn.org/stable/
  • Interpretable Machine Learning https://christophm.github.io/interpretable-ml-book/
  • LIME https://arxiv.org/pdf/1602.04938
  • OpenML (Credit Card Fraud Dataset) https://www.openml.org/d/1597